<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="1400" destroy-on-close :close-on-press-escape="mode != 'show' ? false : true"
			   @closed="$emit('closed')" align-center>
		<el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="100" ref="dialogForm" style="height:650px;overflow:auto;overflow-x:hidden;">
			<el-row :gutter="1">
				<el-col :span="6">
					<el-form-item label="收款单号" prop="collect_code">
						<el-input v-model="form.collect_code" placeholder="收款单号" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="客户" prop="customer_id">
						<el-select v-model="form.customer_id" filterable clearable placeholder="请选择客户" style="width:100%" :disabled="mode == 'collection'">
							<el-option v-for="item in clientList" :key="item.id" :label="item.customer_name" :value="item.id"/>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="收款日期" prop="business_date">
						<el-date-picker v-model="form.business_date" type="date" placeholder="请选择收款日期" style="width: 100%;" :value-format="'YYYY-MM-DD'"></el-date-picker>
					</el-form-item>
				</el-col>
			</el-row>
			<el-col :span="24">
				<el-form-item label="结算信息" prop="detail">
					<sc-form-table ref="table" v-model="form.detail" :addTemplate="addTemplate" placeholder="暂无数据" height="180" show-summary @tableDel="accInput">
						<el-table-column label="结算账户" align="center">
							<template #default="scope">
								<el-select v-model="scope.row.settlement_id" placeholder="请选择" filterable>
									<el-option v-for="item in accountList" :key="item.id" :label="item.account" :value="item.id"/>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column label="收款金额" prop="money" align="center">
							<template #default="scope">
								<el-input v-model="scope.row.money" placeholder="金额" @input="accInput"></el-input>
							</template>
						</el-table-column>
					</sc-form-table>
				</el-form-item>
			</el-col>
			<el-col :span="24">
				<el-form-item label="收款单据" prop="accounts_all">
					<el-button type="primary" size="small" icon="el-icon-plus" @click="checkOrder">选择单据</el-button>
					<sc-form-table ref="table" v-model="form.accounts_all" :addTemplate="accounts_all" placeholder="暂无数据" height="300" hideAdd show-summary @tableDel="orderInput">
						<el-table-column label="业务日期" prop="business_date" align="center"></el-table-column>
						<el-table-column label="单据编号" prop="contract_code" align="center"></el-table-column>
						<el-table-column label="业务类型" prop="type" align="center">
							<template #default="scope">
								{{ scope.row.type == 1 ? '销售订单' : scope.row.type == 2 ? '销售退货' : '其他' }}
							</template>
						</el-table-column>
						<el-table-column label="欠款总额" prop="all_money" align="center"></el-table-column>
						<el-table-column label="收回欠款" prop="pay_money" align="center"></el-table-column>
						<el-table-column label="应收欠款" prop="only_money" align="center"></el-table-column>
						<el-table-column label="本次收款" prop="money" align="center">
							<template #default="scope">
								<el-input v-model="scope.row.money" placeholder="本次收款(元)" clearable @input="orderInput"></el-input>
							</template>
						</el-table-column>
					</sc-form-table>
				</el-form-item>
			</el-col>
			<el-row :gutter="1">
				<el-col :span="12">
					<el-form-item label="备注" prop="remark">
						<el-input v-model="form.remark" placeholder="备注" type="textarea"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="附件" prop="enclosure">
						<sc-upload-file v-model="form.enclosure" :is_same_name="1">
							<el-button type="primary" icon="el-icon-upload">选择文件</el-button>
						</sc-upload-file>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<el-button @click="visible=false">取 消</el-button>
			<el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit(0)">保 存</el-button>
			<el-button v-if="mode == 'add' || mode == 'collection'" type="primary" :loading="isSaveing" @click="submit(1)">保存并审核</el-button>
		</template>
	</el-dialog>
	<collection v-if="dialog.collection" ref="collectionDialog" @success="handleSuccess" @closed="dialog.collection = false" :query="{customer_id:this.form.customer_id,scene:2}"></collection>
</template>

<script>
import Collection from './collection.vue'

export default {
	components: {
		Collection,
	},
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '收款',
				edit: '收款',
				collection: '收款',
				show: '查看'
			},
			visible: false,
			isSaveing: false,
			dialog: {
				collection: false,
			},
			form: {
				business_date: this.moment().format('YYYY-MM-DD'),
				collect_code: "",
				customer_id: "",
				money: "",
				remark: "",
				enclosure: "",
				accounts_all: [],
				detail: [],
			},
			addTemplate: {},
			accounts_all: {},
			accountList: [],    //账户
			clientList: [],     //客户
			order: "",
			countorder: "",
			//验证规则
			rules: {
				customer_id: [{required: true, message: '请选择客户'}],
			},
		}
	},
	mounted() {
		this.getAccount()
		this.getClient()
	},
	methods: {
		/**获取应收账款信息*/
		collectionData(data) {
			this.form.customer_id = data.customer_id
		},
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		//表单提交方法
		submit(e) {
			this.form.is_check = e
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					if (this.form.money != this.countorder) {
						this.$alert("本次收款金额与单据金额不相等，请确认", "提示", {type: 'error'})
					} else {
						this.isSaveing = true;
						var res = await this.$API.finance.shouorder.add.post(this.form);
						this.isSaveing = false;
						if (res.code == 1) {
							this.$emit('success', this.form, this.mode)
							this.visible = false;
							this.$message.success("操作成功")
						} else {
							this.$alert(res.message, "提示", {type: 'error'})
						}
					}
				}
			})
		},
		//表单注入数据
		async setData(data) {
			this.form.id = data.id
			var res = await this.$API.finance.shouorder.detail.get({id: data.id});
			this.form.customer_id = res.data.customer_id
			this.form.collect_code = res.data.collect_code
			this.form.business_date = res.data.business_date
			this.form.remark = res.data.remark
			this.form.enclosure = res.data.enclosure
			this.form.money = res.data.money
			this.form.detail = res.data.detail
			let array = []
			res.data.accounts.map(item => {
				array.push({
					business_date: item.accounts.business_date,
					contract_code: item.accounts.contract && item.accounts.contract.contract_code,
					all_money: item.accounts.money,
					only_money: item.accounts.only_money,
					pay_money: item.accounts.pay_money,
					money: item.money,
					type: item.accounts.type,
				})
			})
			this.form.accounts_all = array
		},
		// 账号
		async getAccount() {
			var res = await this.$API.finance.account.all.get();
			this.accountList = res.data;
		},
		// 客户
		async getClient() {
			var res = await this.$API.client.client.all.get();
			this.clientList = res.data;
		},
		checkOrder() {
			if (this.form.customer_id == '') {
				this.$message.error("请选择客户")
			} else {
				this.dialog.collection = true
				this.$nextTick(() => {
					this.$refs.collectionDialog.open('edit')
				})
			}
		},
		handleSuccess(data) {
			let array = []
			data.map(item => {
				array.push({
					accounts_id: item.id,
					business_date: item.business_date,
					contract_code: item.contract_id !=0 ? item.contract && item.contract.contract_code : item.contractReturn && item.contractReturn.return_code,
					all_money: item.money,
					pay_money: item.pay_money,
					only_money: item.only_money,
					remark: item.remark,
					money: item.only_money,
					type: item.type,
				})
			})
			let existingIds = this.form.accounts_all.map(item => item.accounts_id);
			for (let i = array.length - 1; i >= 0; i--) {
				if (existingIds.includes(array[i].accounts_id)) {
					array.splice(i, 1);
				}
			}
			this.form.accounts_all = [...this.form.accounts_all, ...array]
			this.orderInput()
		},
		accInput() {
			let count_price = 0
			this.form.detail.map(item => {
				if (item.money) {
					count_price = Number(count_price) + Number(item.money)
				}
			})
			this.form.money = count_price
		},
		orderInput() {
			let count_price = 0
			this.form.accounts_all.map(item => {
				if (item.money) {
					count_price = Number(count_price) + Number(item.money)
				}
			})
			this.countorder = (count_price).toFixed(2)
		},
	}
}
</script>

<style>
</style>
